package cn.lcj.basic.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class BaiduAiUtils {

    /**
     * 获取权限token
     * @return 返回示例：
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "VgZ2cKsV6R5ErZkRQ4ya4Q7g";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "vzmZUpU0pdE7L3eyKqV3jlE8NSLMEWHE";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Secret Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    public static Boolean TextCensor(String content) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            //数据从前端传递
            String param = "text=" + content;

            //根据ak和sk获取token
            String accessToken = getAuth();
            //发请求调用第三方的接口进行文本审核，审核通过返回json格式的字符串
            //{"id":1,"conclusion":"合规/不合规"} - json对象 - 对象名获取属性
            String result = HttpUtil.post(url, accessToken, param);
            //将json格式的字符串转成json格式的对象
            JSONObject jsonObject = JSONObject.parseObject(result);
            //获取conclusion的属性值
            String conclusion = jsonObject.getString("conclusion");
            //进行判断
            if("合规".equals(conclusion)){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static Boolean ImgCensor(String imgUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            //图片进行编码
            String imgParam = URLEncoder.encode(imgUrl, "UTF-8");
            //图像传url地址用imgUrl
            String param = "imgUrl=" + imgParam;

            //根据ak和sk获取token
            String accessToken = getAuth();
            String result = HttpUtil.post(url, accessToken, param);

            JSONObject jsonObject = JSONObject.parseObject(result);
            String conclusion = jsonObject.getString("conclusion");
            //进行判断
            if("合规".equals(conclusion)){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


   /* public static void main(String[] args) {
        System.out.println(BaiduAiUtils.TextCensor("sb"));
        System.out.println(BaiduAiUtils.TextCensor("人民公园"));
        System.out.println(BaiduAiUtils.TextCensor("天府新谷"));
        System.out.println(BaiduAiUtils.TextCensor("http://123.207.27.208/group1/sss.png"));
    }*/


    /*
        1.从官网把认证，文本审核，图像审核的方法拷贝进来
        2.导包：httpClient，fastJson
        3.下载工具类：HttpUtil - https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
        4.改造文本审核，图像审核的方法：将返回值改造成布尔值方便判断 - 依据conclusion
        5.细节修改：认证方法JSONObject.parseObject(result)  和 String param = "imgUrl=" + imgParam;
        6.在店铺入驻的业务用起来
        if(!BaiduAiUtils.TextCensor(shop.getName())){
            throw new RuntimeException("店铺名称不合法!!!");
        }
        if(!BaiduAiUtils.ImgCensor("http://123.207.27.208"+shop.getLogo())){
            throw new RuntimeException("店铺Logo不合规!!!");
        }
     */

}
